package br.sed.theenemy.model.dao;

import java.sql.*;

import br.sed.theenemy.business.exception.DBException;

/**
 * 
 * @author Paulo Mendes
 * @email paulo.mendes87@gmail.com
 *
 */
public class Database {
	private String server = "localhost";
	private String user = "the_enemy";
	private String pass = "the_enemy";
	private String db = "the_enemy";
	
//    private String server = "mysql.quenerd.com.br";
//    private String user = "quenerd02";
//    private String pass = "theenemy";
//    private String db = "quenerd02";
	
	private Connection conn = null;
	private Statement stm = null;
	
	// Unica instancia da classe
    protected static Database instanceDB;
	    
	public boolean connectDatabase(){            
        try{
        	Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection( "jdbc:mysql://"+this.server+"/"+this.db+"?user="+this.user+"&password="+this.pass );
            stm = conn.createStatement();  
        }
        catch(ClassNotFoundException e){
        	System.err.println("Classe não encontrada:");
            e.printStackTrace();
            return false;
        }
        catch(Exception e) {
            System.err.println("Erro geral na conexão:");
            e.printStackTrace();
            return false;
        }
        return true;
	}
	public boolean disconnectDatabase(){
		try {
			if(stm!=null){
			    stm.close();
			}
			if(conn!=null){
			    conn.close();
			}
		} 
		catch (SQLException e) {			
			e.printStackTrace();
			return false;
		}
		finally{
			stm = null;
			conn = null;
		}
		return true;
		
	}
	public ResultSet getResults(String sql){				
		try {
			ResultSet result = stm.executeQuery(sql);
			return result;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;		
	}
	public boolean executeSql(String sql, String err_message) throws DBException{
		try {
			stm.execute(sql);
			return true;
		} 
		catch (SQLException e) {
		    throw new DBException("SQL Error", e);
		}
	}
	public Long getId(){
		Long returnId = 0l;
		try {
			ResultSet rs = stm.executeQuery("select the_id from sequences");
			rs.next();
			returnId = rs.getLong("the_id");
			stm.execute("update sequences set the_id = the_id+1");
		} 
		catch (SQLException e) {
			System.err.println("Erro: Add General Id");
			e.printStackTrace();
		}		
		return returnId;
	}
	
	public static Database getInstance(){
        
        // Verifica se ja tem instancia
        if ( instanceDB == null ){         
            instanceDB = new Database();            
        }
        
        return instanceDB;
        
    }
}
